package com.byron.pss.dao.impl;

import java.util.List;

import com.byron.pss.dao.IUserDAO;
import com.byron.pss.domain.User;
import com.byron.pss.template.BeanHandler;
import com.byron.pss.template.BeanListHandler;
import com.byron.pss.template.JdbcTemplate;

public class UserDAOImpl implements IUserDAO {

	@Override
	public void save(User user) {
		String sql = "INSERT INTO t_user VALUES(null,?,?,?)";
		Object[] params = new Object[] { user.getUsername(),
				user.getPassword(), user.getEmail() };
		JdbcTemplate.update(sql, params);
	}

	@Override
	public void delete(Long id) {
		String sql = "DELETE FROM t_user WHERE id=?";
		JdbcTemplate.update(sql, id);
	}

	@Override
	public void update(User user) {
		String sql = "UPDATE t_user SET username=?,password=?,email=? WHERE id=?";
		Object[] params = new Object[] { user.getUsername(),
				user.getPassword(), user.getEmail(), user.getId() };
		JdbcTemplate.update(sql, params);
	}

	@Override
	public User getUser(Long id) {
		String sql = "SELECT * FROM t_user WHERE id=?";
		return JdbcTemplate.query(sql, new BeanHandler<>(User.class), id);
	}

	@Override
	public List<User> query() {
		String sql = "SELECT * FROM t_user";
		return JdbcTemplate.query(sql, new BeanListHandler<>(User.class));
	}

	@Override
	public boolean isExist(String email, String password) {
		String sql = "SELECT * FROM t_user WHERE email=? AND password=?";
		User user = JdbcTemplate.query(sql, new BeanHandler<>(User.class),
				email, password);
		return user == null ? false : true;
	}

	@Override
	public User getUser(String email) {
		String sql = "SELECT * FROM t_user WHERE email=?";
		return JdbcTemplate.query(sql, new BeanHandler<>(User.class), email);
	}
}
